<?php

class tools {

    static function smallText($length, $string, $replacer = '...') {
        if (strlen($string) > $length) {
            return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length + 1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;
        }
        return $string;
    }

    static function float_to_money($float) {
        return number_format($float, 2, ',', '.');
    }

    static function money_to_float($money) {
        return str_replace(',', '.', str_replace('.', '', $money));
        //return str_replace(',', '.', $money);
    }

    static function trunc_valor($valor, $casas = 2) {
        $val = explode(".", $valor);
        return $val[0].".".substr($val[1],  0, $casas);
    }
    static function file_ext($filename) {
        $aux = array_reverse(explode('.', $filename));
        return $aux[0];
    }

    static function htmlentity($var) {
        $array1 = get_html_translation_table(HTML_ENTITIES);
        $array2 = get_html_translation_table(HTML_SPECIALCHARS);
        $diff = array_diff($array1, $array2);
        return strtr(utf8_decode($var), $diff);
    }

    static function retiraAcentos($string) {
        $array1 = array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç", "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");
        $array2 = array("a", "a", "a", "a", "a", "e", "e", "e", "e", "i", "i", "i", "i", "o", "o", "o", "o", "o", "u", "u", "u", "u", "c", "A", "A", "A", "A", "A", "E", "E", "E", "E", "I", "I", "I", "I", "O", "O", "O", "O", "O", "U", "U", "U", "U", "C");
        return str_replace($array1, $array2, $string);
    }

    static function xml_encode($data) {
        $xml = new XmlWriter();
        $xml->openMemory();
        $xml->startDocument('1.0', 'UTF-8');
        $xml->startElement('root');

        if (is_object($data))
            $data = get_object_vars($data);

        self::queue_xml_write($xml, $data);

        $xml->endElement();
        return $xml->outputMemory(true);
    }

    private static function queue_xml_write(XMLWriter $xml, $data) {
        foreach ($data as $key => $value) {

            if (is_object($value))
                $value = get_object_vars($value);

            if (is_array($value)) {
                $xml->startElement($key);
                self::queue_xml_write($xml, $value);
                $xml->endElement();
                continue;
            }

            $xml->writeElement($key, $value);
        }
    }

    /**
     * Mensagem HTML default para envio de emails
     *
     * @return string
     */
    static function toBodyEmail($text) {
        return '<!--
Mensagem HTML default para envio de emails
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>' . self::htmlentity(Kohana::config('company.title')) . '</title>
        <style type="text/css">
            body.queueBody {text-align:center;background-color:white;margin:0px;padding:0px}
            body.queueBody, body.queueBody *{font-size:10px;font-family: Verdana,Arial,Helvetica,sans-serif;color: #FFF}
        </style>
    </head>
    <body class="queueBody">
        <table border="0" align="center" width="600" style="background-color:#191919;">
            <tr>
                <td align="center">
                    <a href="' . self::htmlentity(Kohana::config('company.title')) . '" target="_blank">
                        <img border="0" alt="Cabecalho" src="' . url::site() . 'img/topo_email.jpg">
                    </a>
                </td>
            </tr>
            <tr>
                <td align="left">
                    ' . self::htmlentity($text) . '
                </td>
            </tr>
        </table>
    </body>
</html>';
    }
    
    static function returnTF($val) {
        return isset($val) ? true:false;
    }
    
    static function returnSelected($val1,$val2) {
        
        $selected = "";
        
        if($val1 === $val2)  $selected = "selected";
        
        return $selected;
    }
    
    static function frameVideo() {
        return '<iframe src="/playerVideo/index.php" width="500" height="350"  border="0" frameborder="0"></iframe>';
    }
    
    static function frameVideoSite() {
        return '<iframe src="/playerVideo/site.php" width="350" height="236"  border="0" frameborder="0"></iframe>';
    }
    
    static function returnStatus($sta) {
        return ($sta == 1 ? 'Ativo':'Inativo');
    }
    
    static function returnSN($sta) {
        return ($sta == 1 ? 'Sim':'Não');
    }
    
    static function returnStatusAluno($sta) {
        return ($sta == 1 ? 'Aluno':'Ex-Aluno');
    }
    
    static function getStatusPag() {
        return array('0'=>'Pendente','1'=>'Pago','2'=>'Baixa');
    }
    static function returnStatusPag($sta) {
        $arr = self::getStatusPag();
        return $arr[$sta];
    }
    
    static function returnMuralRecado($sta) { 
        switch ($sta) {
            case '0': return 'Inativo';break;
            case '1': return 'Não Lido';break;
            case '2': return 'Lido';break;
        }
    }
    
    static function ordenacaoTable($nome,$atrr,$t) {
        
        $front = Zend_Controller_Front::getInstance();
        $ord = $front->getRequest()->getParam('ord','');
        if($ord == '') $ord = 'desc';
        else if($ord == 'desc') $ord = 'asc';
        else $ord = 'desc';
        
        $seta = '';
        $_atrr = $front->getRequest()->getParam('atrr','');
        if($ord == 'asc' && $_atrr == $atrr && $_atrr > '') $seta = ' &#9650;';
        else if($ord == 'desc' && $_atrr == $atrr && $_atrr > '') $seta = ' &#9660;';
        
        $link = '<a href="'.$t->urlbase.'/'.$t->modulo.'/'.$t->controller.'/'.$t->action.'?atrr='.$atrr.'&ord='.$ord.'">'.$nome.$seta.'</a>';
        return $link;
    }
    
    static function returnStatusAlunoMat($cod) {
        $status = '';
        
        //aluno
        $where = 'ALU_ID = ' . $cod;
        $r_alu = new Sistema_Model_DbTable_Aluno();
        $r_alu = $r_alu->fetchRow($where);
        
        // matricula      
        $where = 'ALU_ID = ' . $cod. ' and MAT_STA = 1';
        $r_mat = new Sistema_Model_DbTable_Matricula();
        $r_mat = $r_mat->fetchRow($r_mat->select()->where($where)->order('MAT_ID desc'));
        
        if(!isset($r_mat['CUR_ID'])){
            return $status = 'Ex-Aluno';
        } 
        // curso
        $where = 'CUR_ID = ' . (int) $r_mat['CUR_ID'];
        //$where = 'CUR_ID = ' . (int) $row['CUR_ID'];
        $cur = new Sistema_Model_DbTable_Curso();
        $r_cur = $cur->fetchRow($where);
        
        if($r_cur->CUR_STA == 1){
            $status =  'Ativo';
        }
        else{
            $status = 'Ex-Aluno';
        }
        // fila de espera
        $where = 'MAT_ID = ' . (int) $r_mat['MAT_ID'];
        $fila = new Sistema_Model_DbTable_Filamatricula();
        $r_fila = $fila->fetchRow($where);
        if(isset($r_fila->FIL_ID) && $r_fila->FIL_ID > 0) $status =  'FILA DE ESPERA';        
        
        // desativa aluno se não tive mais nada
        if($r_alu->ALU_STA == 1 && $status == 'Ex-Aluno'){
            $r_alu = new Sistema_Model_DbTable_Aluno();
            $r_alu->update(array('ALU_STA'=>'0'),'ALU_ID = ' . $cod);
        }
        
        return $status;
    }
        
    
}